import Vue from 'vue'
import { Message } from 'element-ui'
import { getSession } from '@/utils/session'
//json转params
export function json2params(json) {
  var params = Object.keys(json)
    .map(function(key) {
      return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
    })
    .join('&')
  return '?' + params
}
//清除html标签
export function removeHtmlTab(data) {
  return data.replace(/<[^>]*>|<\/[^>]*>/gm, '')
}
export function deep(dest, obj) {
  var o = dest
  for (var key in obj) {
    if (typeof obj[key] === 'object') {
      o[key] = obj[key].constructor === Array ? [] : {}
      deep(o[key], obj[key])
    } else {
      o[key] = obj[key]
    }
  }
  return o
}
// 检查必须为整数
export function checkNumber(value, minLimit, maxLimit) {
  value = Math.floor(value)
  if (value < minLimit) {
    value = minLimit
  } else if (value > maxLimit) {
    value = maxLimit
  }
  return value
}
//数组去重
export function unique(arr) {
  for (var i = 0, len = arr.length; i < len; i++) {
    for (var j = i + 1, len = arr.length; j < len; j++) {
      if (arr[i] === arr[j]) {
        arr.splice(j, 1)
        j-- // 每删除一个数j的值就减1
        len-- // j值减小时len也要相应减1（减少循环次数，节省性能）
      }
    }
  }
  return arr
}

export function uniqueById(arr) {
  for (var i = 0, len = arr.length; i < len; i++) {
    for (var j = i + 1, len = arr.length; j < len; j++) {
      if (arr[j] && arr[i].id === arr[j].id) {
        arr.splice(j, 1)
        j-- // 每删除一个数j的值就减1
        len-- // j值减小时len也要相应减1（减少循环次数，节省性能）
      }
    }
  }
  return arr
}

//消息提醒 - 未登录
export function loginTip() {
  Message({
    message: '请先登录',
    type: 'warning',
  })
}
//消息提醒 - 预览模式
export function previewTip() {
  Message({
    message: '预览模式不可进行此操作',
    type: 'warning',
  })
}

export function errMsg(msg) {
  Message({
    message: msg,
    type: 'error',
  })
}

export function warnMsg(msg) {
  Message({
    message: msg,
    type: 'warning',
  })
}

export function successMsg(msg) {
  Message({
    message: msg,
    type: 'success',
  })
}

//删除提示
export function deleteTips(callback, tipsCon, btnTxt) {
  this.$confirm(tipsCon || '确定要删除吗?', '提示', {
    confirmButtonText: btnTxt || '删除',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      callback()
    })
    .catch(() => {})
}

//通过路由名称跳转
export function routeToByName(name) {
  this.$router.push({ name })
}

//关闭弹窗清空表单
export function $reset(formRef) {
  this.$refs[formRef].resetFields()
}
//返回上一层
export function $back() {
  this.$router.go(-1)
}
//关闭弹窗清空表单
export function toFixeds(data, place) {
  place = place || 1
  return Number(data).toFixed(place)
}
//按钮权限
export function $button(data) {
  let { userType } = this.$store.getters
  if (userType == 1) {
    return true
  }
  if (!data) return
  if (typeof data != 'string') {
    data = data.toString()
  }
  let buttons = getSession('buttons').split(',')
  if (!buttons) return
  return buttons.includes(data)
}

//loading
export function openLoading() {
  const loading = this.$loading({
    lock: true,
    text: '正在加载...',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  setTimeout(function() {
    loading.close()
  }, 5000)
  return loading
}
//默认图片
export function defaultLibraryImg(type) {
  switch (type) {
    case 1:
      return this.defaultCourseImg
    case 2:
      return this.defaultSpecialtyImg
    case 3:
      return this.defaultArmImg
    default:
      return this.defaultCourseImg
  }
}

//百分比计算
export function getPercent(num, total) {
  num = parseFloat(num)
  total = parseFloat(total)
  if (isNaN(num) || isNaN(total)) {
    return 0
  }
  return total <= 0 ? '0%' : Math.round((num / total) * 10000) / 100.0 + '%'
}

//拉平数组
export function flatObj(arr, children = 'childList') {
  var newArr = []
  arr.forEach((element) => {
    newArr.push(element)
    if (element[children]) {
      newArr.push.apply(newArr, flatObj(element[children], children))
      delete element[children]
    } else {
    }
  })
  return newArr
}
